import axios from "axios";
import {getAccessToken, getRefreshToken} from '@/utils/auth'
import { Message } from 'element-ui'

const service = axios.create({
    baseURL: '/',
    headers: {
        get: {
            'Content-Type': 'application/x-www.urlencoded;charset=utf-8'
        },
        post: {
            'Content-Type': 'application/json;charset=utf-8'
        }
    },
    timeout: 30000,
    withCredentials: false
})

service.interceptors.request.use(config => {
    if(getAccessToken()) {
        config.headers['Blade-Auth']=`Bearer ` + getAccessToken()
        config.headers['Authorization']='Basic Zml6ejpmaXp6X3NlY3JldA=='
    }else {
        config.headers['Authorization']='Basic Zml6ejpmaXp6X3NlY3JldA=='
    }
    return config;
}, error => {
    Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(async res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    const msg = res.data.msg;
    if(code === 401) {
        console.log('401');
    } else if(code === 400) {
        Message({
            message: msg,
            type: 'error'
        })
        return Promise.reject(new Error(msg))
    } else {
        if(res.headers.filename) {
            return res;
        }
        return res.data
    }
}, error => {
    return Promise.reject(error)
})

export {service as request}